using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace TheLogWatcher
{
    public partial class MainWindow : Form
    {

        #region TOOLSTRIP MENU EVENTS

        private void toolStripFileOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog();
        }

        private void toolStripFileClose_Click(object sender, EventArgs e)
        {
            this.listView.VirtualMode = false;
            this.listView.VirtualListSize = 0;
            this.listView.Items.Clear();
            this.dataAccess = null;
            UpdateAllEntriesInfoStatusbar();
            this.Text = "The Log Watcher";
        }

        private void toolStripFileExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void toolStripHistoryItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            string filename = (string)item.Tag;

            if (this.dataAccess != null && this.dataAccess.FnProvider != null)
            {
                this.dataAccess.FnProvider.ResetFileIterator();
                LogFile file = this.dataAccess.FnProvider.GetNextFile();
                if (file != null && file.Filename != null)
                {
                    string currentOpened = file.Filename;
                    if (currentOpened != null && currentOpened.Equals(filename, StringComparison.OrdinalIgnoreCase))
                    {
                        DialogResult result = MessageBox.Show("Selected file is currently open, reload ?", "File Already Open", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                        if (result == DialogResult.No)
                        {
                            return;
                        }
                    }
                }
            }

            LoadLogfile(filename);
        }
        
        private void toolStripSettingsUserSettings_Click(object sender, EventArgs e)
        {
            UserSettings settingsForm = new UserSettings();
            DialogResult result = settingsForm.ShowDialog();
            if (result == DialogResult.OK)
            {
                LoadWindowSettings();
            }
        }

        private void toolStripSettingsPerformanceSettings_Click(object sender, EventArgs e)
        {
            PerformanceSettings settingsForm = new PerformanceSettings();
            DialogResult result = settingsForm.ShowDialog();
            if (result == DialogResult.OK)
            {
                this.data = null;
                if (this.dataAccess != null && this.dataAccess.FnProvider != null)
                {
                    LoadLogfile(this.dataAccess.FnProvider.OriginalFilename);
                }
            }
        }

        private void toolStripSettingsLogInformation_Click(object sender, EventArgs e)
        {
            if (this.dataAccess == null || this.dataAccess.CurrentLogFormat == null)
            {
                MessageBox.Show("Open a file first.");
                return;
            }
            LogInformation info = new LogInformation(this.dataAccess.CurrentLogFormat);
            info.Show();
        }

        private void toolStripHelpAbout_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.ShowDialog();
        }

        #endregion

        #region DIFFERENT EVENTS

        ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter();

        //private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
        //{
            //if (e.Column == lvwColumnSorter.SortColumn)
            //{
            //    if (lvwColumnSorter.Order == SortOrder.Ascending)
            //    {
            //        lvwColumnSorter.Order = SortOrder.Descending;
            //    }
            //    else
            //    {
            //        lvwColumnSorter.Order = SortOrder.Ascending;
            //    }
            //}
            //else
            //{
            //    lvwColumnSorter.SortColumn = e.Column;
            //    lvwColumnSorter.Order = SortOrder.Ascending;
            //}
            //listView.Sort();
        //}

        private void contextMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            item.Checked = !item.Checked;
            int column = (int)item.Tag;
            this.colMan.changeVisibility(column, item.Checked);
            //CreateListViewContextMenuItems();
        }
                
        private void listView_DoubleClick(object sender, EventArgs e)
        {
            if (listView.SelectedIndices.Count != 0)
            {
                // What is selected
                int chosen = listView.SelectedIndices[0];
                int elements = this.listView.VirtualListSize;
                LogEntryView lv = new LogEntryView(this, chosen, elements);
                lv.Show();
            }
        }

        private void pictureBoxTypeButton_Click(object sender, EventArgs e)
        {
            PictureBox box = (PictureBox)sender;
            string loadThis = null;
            if (this.dataAccess != null && this.dataAccess.FnProvider != null)
            {
                loadThis = this.dataAccess.FnProvider.OriginalFilename;
            }

            // INFO button check
            if (btnINFO.Image == info2 && btnINFO == box)
            {
                sets.SelectedTypes.Add(MessageTypes.INFO.ToString());
            }
            else if (btnINFO.Image == info && btnINFO == box && sets.SelectedTypes.Count > 1)
            {
                sets.SelectedTypes.Remove(MessageTypes.INFO.ToString());
            }

            // DEBUG button check
            if (btnDEBUG.Image == debug2 && btnDEBUG == box)
            {
                sets.SelectedTypes.Add(MessageTypes.DEBUG.ToString());
            }
            else if (btnDEBUG.Image == debug && btnDEBUG == box && sets.SelectedTypes.Count > 1)
            {
                sets.SelectedTypes.Remove(MessageTypes.DEBUG.ToString());
            }

            // WARN button check
            if (btnWARN.Image == warn2 && btnWARN == box)
            {
                sets.SelectedTypes.Add(MessageTypes.WARN.ToString());
            }
            else if (btnWARN.Image == warn && btnWARN == box && sets.SelectedTypes.Count > 1)
            {
                sets.SelectedTypes.Remove(MessageTypes.WARN.ToString());
            }

            // ERROR button check
            if (btnERROR.Image == error2 && btnERROR == box)
            {
                sets.SelectedTypes.Add(MessageTypes.ERROR.ToString());
            }
            else if (btnERROR.Image == error && btnERROR == box && sets.SelectedTypes.Count > 1)
            {
                sets.SelectedTypes.Remove(MessageTypes.ERROR.ToString());
            }

            // FATAL button check
            if (btnFATAL.Image == fatal2 && btnFATAL == box)
            {
                sets.SelectedTypes.Add(MessageTypes.FATAL.ToString());
            }
            else if (btnFATAL.Image == fatal && btnFATAL == box && sets.SelectedTypes.Count > 1)
            {
                sets.SelectedTypes.Remove(MessageTypes.FATAL.ToString());
            }
            sets.Save();
            changeButtonStates();
            this.setListViewVirtualMode();
            RedrawListView();
        }

        private void RedrawListView()
        {
            if (this.listView.InvokeRequired)
            {
                this.listView.Invoke(new MethodInvoker(RedrawListView));
            }
            else
            {
                this.listView.VirtualMode = false;
                if (this.dataAccess != null && this.dataAccess.Indices != null && this.dataAccess.Indices.Count > 0)
                {
                    this.dataAccess.SortListViewEntries();
                    this.listView.VirtualListSize = this.dataAccess.SortedIndices.Count;
                }
                Console.WriteLine("ITEMS:  " + this.listView.VirtualListSize.ToString());
                if (this.listView.VirtualListSize > 0)
                {
                    try
                    {
                        //this.listView.RedrawItems(0, this.listView.VirtualListSize - 1, true);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("RedrawItems: " + ex.Message);
                    }
                }

                // Update statusbar "All Entries"
                UpdateAllEntriesInfoStatusbar();
                this.listView.VirtualMode = true;
            }
        }

        #endregion

        #region WINDOW EVENTS

        private void MainWindow_Resize(object sender, EventArgs e)
        {
            // Setting window size
            sets.MainWindowWidth = this.Width;
            sets.MainWindowHeight = this.Height;
            sets.Save();
        }

        private void MainWindow_DragOver(object sender, DragEventArgs dea)
        {
            if (dea.Data.GetDataPresent(DataFormats.FileDrop))
            {
                dea.Effect = DragDropEffects.Link;
            }
        }

        private void MainWindow_DragDrop(object sender, DragEventArgs dea)
        {
            if (dea.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])dea.Data.GetData(DataFormats.FileDrop);
                if (files != null && files.Length > 0)
                {
                    bool success = LoadLogfile(files[0]);
                    if (!success)
                    {
                        MessageBox.Show("Cannot open logfile !", "Loading Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }
                }
            }
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            LoadWindowSettings();

            // SETTING LAST LOADED FILE
            setLastLoadedFileDialog();

            // Iterator settings for active row reload operations
            setListViewVirtualMode();

            // Update statusbar "All Entries"
            UpdateAllEntriesInfoStatusbar();
        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveWindowSettings();
        }

        #endregion
    }
}
